/*
 * @Description:
 * @Author: cgt
 * @Date: 2021-10-20 17:40:38
 * @LastEditors: cgt
 * @LastEditTime: 2022-01-20 17:36:47
 */
import {
  parse
} from '../../../../mapUtils/Geojson2WktUtil';
import {
  projectLngLatToWebMercator
} from '../../../../mapUtils/CoordinateUtil';
import {
  debounce
} from 'throttle-debounce';
import IGridTool from '../IGridTool';
import Prefix from '../../constant/Prefix';

/**
 * 现状电网图层工具箱
 * @implements {IGridTool}
 */
class ActualGridTool extends IGridTool {
  constructor(_top, _impl) {
    super(_top, _impl);
    this.name = 'ActualGridTool';
    this.desc = '现状电网图层工具箱';
    this.layeridPrefix = Prefix['ActualGrid'];
    this._refresh = debounce(this.THROTTLE_DURATION, () => {
      console.log('refresh throttle');
      // if(this.startzoom) {
      //   this.startzoom = false;
      //   return;
      // }
      this.refresh(this.useNewService);
    }).bind(this);
  }

  /**
   * 刷新现状图层
   * @override
   */
  async refresh(useNewService) {
    this.useNewService = !!useNewService;
    console.log('refresh');
    this.setCurrentGridTool(this);
    if (this.isLocked()) {
      return;
    }
    // 当前请求时间
    let currentRequestTime = this.latestRequestTime = new Date().getTime();
    // 获取当前缩放等级下配置的图层列表
    var data = await this.getApi().PwghGhsjScTxfw.figure.get_figure_getEquitpType({
      params: {
        zoom: this.getTool('BaseMapTool').getZoom(),
        schemaid: this.searchOption.schemaid
      }
    });
    // 过期请求不处理
    if (this._isOutDate(currentRequestTime)) {
      return;
    }
    let sbzlxs = data.datas;
    if (!sbzlxs) {
      return;
    }
    // 获取范围、缩放等级
    let extent = this.getTool('BaseMapTool').getBounds();
    let shape = parse(window.turf.polygon(projectLngLatToWebMercator(turf.bboxPolygon(extent).geometry.coordinates)).geometry);
    let zoom = this.getTool('BaseMapTool').getZoom();
    let schema = this.searchOption.schema || this.getConfig().get('SCHEMA');
    this.cancelOutDateRequest();
    var firstRequest = true;
    // 拼接请求数据
    // 显示方案①：数据先来先出
    /*
    sbzlxs.forEach(({ sblx, oid }) => {
      this.getApi()
        .PwghGhsjScTxfw.figure.post_figure_showGhdwEquip(
          Object.assign({}, this.searchOption, {
            zoom,
            sblx,
            shape,
            oid,
            schema,
            cancelToken: this.appendCancelToken(),
          }),
        )
        .then((res) => {
          // 过期请求不处理
          !this._isOutDate(currentRequestTime) &&
            this._showBySgmapLayer(
              [
                {
                  sblx,
                  res,
                },
              ],
              firstRequest,
            );
          firstRequest = false;
        })
        .catch((err) => {
          console.log("post_figure_showGhdwEquip error : ", err);
        });
    });
    */
    // 显示方案②：数据都返回后再出
    var serviceName = this.useNewService ? 'post_figure_showGhdwEquipNew' : 'post_figure_showGhdwEquip';
    var resList = await Promise.all(sbzlxs.map(({
      sblx,
      oid
    }) => {
      return new Promise((resolve) => {
        this.getApi()
          // 旧版出图服务接口
          // .PwghGhsjScTxfw.figure.post_figure_showGhdwEquip(
          // 新版出图服务接口
          // .PwghGhsjScTxfw.figure.post_figure_showGhdwEquipNew(
          .PwghGhsjScTxfw.figure[serviceName](
            Object.assign({}, this.searchOption, {
              zoom,
              sblx,
              shape,
              oid,
              schema,
              cancelToken: this.appendCancelToken(),
            })
          ).then((res) => {
            resolve({
              res: res,
              sblx
            });
          }).catch(() => {
            resolve({
              res: {},
              sblx
            });
          });
      });
    }));
    if (!this._isOutDate(currentRequestTime)) {
      this._showBySgmapLayer(resList, firstRequest);
    }
  }
}

export default ActualGridTool;